package com.fans.oauths.server.oauth2.service;

import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import com.fans.oauths.server.oauth2.dao.UserDao;
import com.fans.utils.BlankUtils;


/**
 * @author fans
 * @date 2017年11月12日 上午22:57:51
 */
@Component
public class SysUserDetailsService implements UserDetailsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        Map<String, Object> sysUser = userDao.getUser(username);

        if (BlankUtils.isBlank(sysUser)) {
        	logger.info(username+" ---> 该用户名不存在!");
            throw new AuthenticationCredentialsNotFoundException("用户名不存在!");
        }

        String password = String.valueOf(sysUser.get("password"));

        User user = new User(username, password,     
                true, true, true, true, //是否有效，账户是否过期，密码是否过期，是否锁定，
                AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER,ROLE_ADMIN,sys:user:add"));

        return user;
    }


}
